package com.lwj.liwanjia.view.fragment.shouye;


import android.content.Intent;
import android.graphics.Rect;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baoyz.widget.PullRefreshLayout;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.HomeClassifAdapter;
import com.lwj.liwanjia.base.BaseFragment;
import com.lwj.liwanjia.base.MyApplication;
import com.lwj.liwanjia.bean.BannerBean;
import com.lwj.liwanjia.bean.GwcNumberBean;
import com.lwj.liwanjia.bean.HomeBean;
import com.lwj.liwanjia.impl.BannerView;
import com.lwj.liwanjia.impl.GwcNumberView;
import com.lwj.liwanjia.impl.HomeClassifyView;
import com.lwj.liwanjia.presenter.BannerPresenter;
import com.lwj.liwanjia.presenter.GwcNumberPresenter;
import com.lwj.liwanjia.presenter.HomeClassifyPresenter;
import com.lwj.liwanjia.utils.GlideImageLoader;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.search.SearchActivity;
import com.lwj.liwanjia.view.activity.shop.ShopHomeActivity;
import com.lwj.liwanjia.view.activity.supermarket.SuperMarketActivity;
import com.lwj.liwanjia.view.activity.work.WorkHomeActivity;
import com.lwj.liwanjia.view.activity.yikatong.YiKaTongActivity;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class MianFragment extends BaseFragment implements AMapLocationListener, BannerView, HomeClassifyView, GwcNumberView, PullRefreshLayout.OnRefreshListener, OnBannerClickListener, RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.loaction)
    TextView loaction;
    @BindView(R.id.banners)
    Banner banners;
    @BindView(R.id.rlv_home_classify)
    SuperRecyclerView homeRlv;//功能分类
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.fragment_container2)
    FrameLayout fragmentContainer2;
    @BindView(R.id.refresh_layout)
    PullRefreshLayout refreshLayout;

    //轮播图
    private BannerPresenter bannerPresenter;
    private List<String> imagesList = new ArrayList<>();
    //功能分类
    private HomeClassifyPresenter homeClassifyPresenter;
    private HomeClassifAdapter adapter;
    private List<HomeBean.DataBean> classifyList = new ArrayList<>();
    //商品展示
    private List<Fragment> fragments = new ArrayList<>();
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private Fragment mFragment;
    private GwcNumberPresenter gwcNumberPresenter;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void initView(View view) {
        //定位
        initClient();
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 4);
        homeRlv.setLayoutManager(manager);
        homeRlv.setRefreshEnabled(false);
        homeRlv.setLoadMoreEnabled(false);
        refreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_WATER_DROP);
        refreshLayout.setOnRefreshListener(this);
        homeRlv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                //不是第一个的格子都设一个左边和底部的间距
                outRect.left = (int) getResources().getDimension(R.dimen.x4);
                outRect.bottom = (int) getResources().getDimension(R.dimen.x4);
                //   由于每行都只有4个，所以第一个都是4的倍数，把左边距设为0
                if (parent.getChildLayoutPosition(view) % 4 == 0) {
                    outRect.left = 0;
                }
            }
        });
        adapter = new HomeClassifAdapter(getActivity(), classifyList);
        homeRlv.setAdapter(adapter);
        getFragments();
        radioGroup.setOnCheckedChangeListener(this);
        bannerPresenter = new BannerPresenter(this);
        gwcNumberPresenter = new GwcNumberPresenter(this);
        homeClassifyPresenter = new HomeClassifyPresenter(this);
        clickListener();
    }

    /**
     * 初始化定位
     */
    private void initClient() {
        //初始化定位
        mLocationClient = new AMapLocationClient(MyApplication.getInstance());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        mLocationOption.setGpsFirst(true);
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 商品展示
     */
    private void getFragments() {
        fragments.add(new PromotionFragment());
        fragments.add(new NewProductFragment());
        fragments.add(new SeckillFragment());
        fragments.add(new LikeFragment());
        mFragment = fragments.get(0);
        fragmentManager = getActivity().getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.fragment_container2, mFragment).commit();
    }

    /**
     * 点击事件
     */
    private void clickListener() {
        //分类点击事件
        adapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                switch (classifyList.get(position).getIndexButtonName()) {
                    case "利万嘉超市":
                        startActivity(new Intent(getActivity(), SuperMarketActivity.class));
                        break;
                    case "网上商城":
                        startActivity(new Intent(getActivity(), ShopHomeActivity.class));
                        break;
                    case "二手市场":
//                        startActivity(new Intent(getActivity(), ShiChangHomeActivity.class));
                        Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                        break;
                    case "农资市场":
//                        startActivity(new Intent(getActivity(), NongZiHomeActivity.class));
                        Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                        break;
                    case "健康管理":
//                        startActivity(new Intent(getActivity(), JiangKangGuanLiActivity.class));
                        Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                        break;
                    case "物流快递":
//                        startActivity(new Intent(getActivity(), LogisticsActivity.class));
                        Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                        break;
                    case "本地服务":
//                        startActivity(new Intent(getActivity(), BenDiHomeActivity.class));
                        Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                        break;
                    case "新闻视频":
//                        startActivity(new Intent(getActivity(), XinWenShiPinHomeActivity.class));
                        Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                        break;
                    case "我的秘书":
//                        startActivity(new Intent(getActivity(), MiShuHomeActivity.class));
                        Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                        break;
                    case "我的工作":
                        startActivity(new Intent(getActivity(), WorkHomeActivity.class));
                        break;
                    case "一卡通":
                        startActivity(new Intent(getActivity(), YiKaTongActivity.class));
                        break;
                    case "更多":
                        Toast.makeText(getActivity(), "暂无更多", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    @Override
    protected void initData() {
        homeClassifyPresenter.getClassifyData();
        bannerPresenter.getBannerData();
        gwcNumberPresenter.getGwcNumber(SpfUtils.getSpfUtils(getActivity()).getToken());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mian;
    }


    @Override
    public void showProgress() {
        // progress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        // progress.setVisibility(View.GONE);
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(getActivity(), "数据加载失败！", Toast.LENGTH_SHORT).show();
        refreshLayout.setRefreshing(false);
    }

    /*获取当前购物车物品数量*/
    @Override
    public void getGwcNumber(GwcNumberBean gwcNumberBean) {
        if (gwcNumberBean.getState() == 1) {
            SpfUtils.getSpfUtils(getActivity()).setGwcNumber(gwcNumberBean.getData());
        }
    }

    /*功能分类*/
    @Override
    public void getClassifyData(HomeBean homeBean) {
        if (homeBean.getState() == 1) {
            classifyList.clear();
            classifyList.addAll(homeBean.getData());
            adapter.notifyDataSetChanged();
        }
        refreshLayout.setRefreshing(false);
    }

    /*轮播图*/
    @Override
    public void getBannerData(BannerBean bannerBean) {
        if (bannerBean.getState() == 1) {
            imagesList.clear();
            imagesList.addAll(bannerBean.getData());
            if (imagesList.size() > 0) {
                banners.setImages(imagesList)
                        .setImageLoader(new GlideImageLoader())
                        .setOnBannerClickListener(this)
                        .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                        .setDelayTime(4000)
                        .start();
            }
            refreshLayout.setRefreshing(false);
        }
    }

    //轮播图点击事件
    @Override
    public void OnBannerClick(int position) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (homeClassifyPresenter != null) {
            homeClassifyPresenter = null;
        }
        if (bannerPresenter != null) {
            bannerPresenter = null;
        }
        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        }
    }

    /**
     * 商品活动切换
     *
     * @param group
     * @param checkedId
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_promotion://促销商品
                switchFragment(fragments.get(0));
                break;
            case R.id.rb_new_product://新品展示
                switchFragment(fragments.get(1));
                break;
            case R.id.rb_seckill://秒杀商品
                switchFragment(fragments.get(2));
                break;
            case R.id.rb_like://猜你喜欢
                switchFragment(fragments.get(3));
                break;
        }
    }

    @OnClick({R.id.search_layout, R.id.xiaoxi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_layout://搜索
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.xiaoxi://消息
//                startActivity(new Intent(getActivity(), XiaoxiActivity.class));
                Toast.makeText(getActivity(), "暂未开通", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 商品展示切换
     *
     * @param fragment
     */
    private void switchFragment(Fragment fragment) {
        //判断当前显示的Fragment是否就是切换的Fragment
        if (mFragment != fragment) {
            //判断切换的fragment是否已经添加过
            if (!fragment.isAdded()) {
                //如果没有，先把当前的fragment隐藏，再添加新的fragment
                getActivity().getSupportFragmentManager().beginTransaction().hide(mFragment)
                        .add(R.id.fragment_container2, fragment).commit();
            } else {
                getActivity().getSupportFragmentManager().beginTransaction().hide(mFragment).show(fragment).commit();
            }
            mFragment = fragment;
        }
    }

    /**
     * 定位
     *
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation.getErrorCode() == 0) {
            loaction.setText(aMapLocation.getDistrict());
            SpfUtils.getSpfUtils(getActivity()).setProvince(aMapLocation.getProvince());
            SpfUtils.getSpfUtils(getActivity()).setCity(aMapLocation.getCity());
            SpfUtils.getSpfUtils(getActivity()).setDistrict(aMapLocation.getDistrict());
            double latitude = aMapLocation.getLatitude();
            double longitude = aMapLocation.getLongitude();
            SpfUtils.getSpfUtils(getActivity()).setLatitude((float) latitude);
            SpfUtils.getSpfUtils(getActivity()).setLongitude((float) longitude);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
        mLocationClient.startLocation();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initData();
            mLocationClient.startLocation();
        }
    }

    @Override
    public void onRefresh() {
        initData();
    }

}
